package com.mask.im.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mask.im.business.model.entity.MailDraft;
import com.mask.im.business.common.exception.BusinessException;
import com.mask.im.business.mapper.MailDraftMapper;
import com.mask.im.business.common.model.RestResponse;
import com.mask.im.business.service.MailDraftService;
import com.mask.im.business.common.util.MaskIMSecurityUtils;
import com.mask.im.business.common.util.PageUtil;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.mask.im.business.common.constant.CommonConstant.NORMAL_STATE;
import static com.mask.im.business.common.constant.CommonConstant.RECYCLE_BIN;


/**
 * @author jian
 */
@Service
public class MailDraftServiceImpl extends ServiceImpl<MailDraftMapper, MailDraft> implements MailDraftService {

	@Override
	public RestResponse<Page<MailDraft>> getMailDraft(String mail,Integer status) {
		Integer userId = MaskIMSecurityUtils.getUserId();
		Page<MailDraft> mailDraftPage = this.baseMapper.selectPage(new Page<>(PageUtil.getCurrentPage(), PageUtil.getSize()),
				new LambdaQueryWrapper<MailDraft>()
						.eq(MailDraft::getSender, userId)
						.eq(MailDraft::getStatus,status)
						.like(Objects.nonNull(mail),MailDraft::getEmail,mail)
						.orderByDesc(MailDraft::getUpdateTime)
						);
		return RestResponse.ok(mailDraftPage);
	}

	@Override
	public RestResponse<String> deleteMailDraft(Integer id) {
		MailDraft mailDraft = this.baseMapper.selectById(id);
		if (Objects.nonNull(mailDraft)){
			mailDraft.setStatus(RECYCLE_BIN);
			this.baseMapper.updateById(mailDraft);
			return RestResponse.ok("删除成功");
		}
		return RestResponse.fail("找不到该邮件草稿，刷新试试");
	}

	@Override
	public RestResponse<String> saveMailDraft(MailDraft mailDraft) {
		Integer userId = MaskIMSecurityUtils.getUserId();
		mailDraft.setStatus(NORMAL_STATE);
		mailDraft.setSender(userId);
		this.baseMapper.insert(mailDraft);
		return RestResponse.ok();
	}

	@Override
	public RestResponse<String> recoverMailDraft(Integer id) {
		MailDraft mailDraft1 = this.baseMapper.selectById(id);
		if (mailDraft1==null){
			throw new BusinessException("找不到该邮件");
		}
		MailDraft mailDraft = MailDraft.builder()
				.id(id)
				.status(NORMAL_STATE).build();
		this.baseMapper.updateById(mailDraft);
		return RestResponse.ok();
	}

	@Override
	public RestResponse<MailDraft> getMailDraftById(Integer id) {
		MailDraft mailDraft = this.baseMapper.selectById(id);
		return RestResponse.ok(mailDraft);
	}

	@Override
	public RestResponse<String> permanentlyDelete(Integer id) {
		MailDraft mailDraft = MailDraft.builder().id(id).status(2).build();
		this.baseMapper.updateById(mailDraft);
		return RestResponse.ok();
	}
}

